import { createApp } from 'vue'
import { createPinia } from 'pinia'
import ElementPlus from 'element-plus'
import zhCn from 'element-plus/dist/locale/zh-cn.mjs'
import 'element-plus/dist/index.css'
import './style.css'
import App from './App.vue'
import router from './router'
import './mock/index.js'  // Import mock data
import { isAuthenticated } from './utils/auth.js'
import * as ElementPlusIconsVue from '@element-plus/icons-vue'
import { hasPermission, hasAnyPermission } from './utils/auth'

const app = createApp(App)
const pinia = createPinia()

// 注册所有图标
for (const [key, component] of Object.entries(ElementPlusIconsVue)) {
  app.component(key, component)
}

// 注册权限指令
app.directive('permission', {
  mounted(el, binding) {
    const { value } = binding
    if (value) {
      const permitted = hasPermission(value)
      if (!permitted) {
        if (el.parentNode) {
          el.parentNode.removeChild(el);
        } else {
          el.style.display = 'none';
        }
      }
    }
  }
})

app.directive('any-permission', {
  mounted(el, binding) {
    const { value } = binding
    if (value && Array.isArray(value)) {
      const permitted = hasAnyPermission(value)
      if (!permitted) {
        if (el.parentNode) {
          el.parentNode.removeChild(el);
        } else {
          el.style.display = 'none';
        }
      }
    }
  }
})

app.use(pinia)
app.use(ElementPlus, {
  locale: zhCn,
})
app.use(router)
app.mount('#app')

// 检测是否有已经登录的用户，如果没有，则导航到登录页
if (!isAuthenticated() && router.currentRoute.value.path !== '/login') {
  router.push('/login')
}
